package controllers

import (
	"ecomserver/common"
	"ecomserver/models"
	"encoding/base64"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils"
	"github.com/gomodule/redigo/redis"
	"regexp"
	"strconv"
)

type UserController struct {
	beego.Controller
}

//显示注册页面
func (this *UserController) ShowReg() {
	this.TplName = "register.html"
}
func (this *UserController) errorReturn(str string) {
	this.Data["errmsg"] = str
	this.TplName = "register.html"
}
func (this *UserController) sendEmail(enamePos string, id int) {
	emailConfig := `{"username":"1006218237@qq.com","password":"zaceocgtfcikbbaa","host":"smtp.qq.com","port":587}`
	emailConn := utils.NewEMail(emailConfig)
	if emailConn == nil {
		beego.Info("emailConfig 错误")
		return
	}
	emailConn.From = "1006218237@qq.com"
	emailConn.To = []string{enamePos}
	emailConn.Subject = "你要注册啦"

	//这里发送激活请求地址
	emailConn.Text = "http://192.168.40.133:8080/active?id=" + strconv.Itoa(id)
	error := emailConn.Send()
	if error != nil {
		beego.Info(error)
		beego.Info("email:" + enamePos + "id:" + strconv.Itoa(id))
	}
}

//处理注册数据
func (this *UserController) HandleReg() {
	//1.获取数据
	user_name := this.GetString("user_name")
	pwd := this.GetString("pwd")
	cpwd := this.GetString("cpwd")
	email := this.GetString("email")
	allow := this.GetString("allow")
	//2.校验数据
	if user_name == "" || pwd == "" || cpwd == "" || email == "" || allow == "" {
		this.errorReturn("数据不完整，请重新输入")
		return
	}
	if pwd != cpwd {
		this.errorReturn("两次密码输入不一致，请重新注册")
		return
	}
	reg, _ := regexp.Compile(`^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$`)
	if res := reg.FindString(email); res == "" {
		this.errorReturn("邮箱格式不正确")
		return
	}
	//3.处理数据
	o := orm.NewOrm()
	var user models.User
	user.Name = user_name
	user.PassWord = pwd
	user.Email = email
	_, err := o.Insert(&user)

	if err != nil {
		this.errorReturn("用户名已经存在，请重新注册")
		return
	}
	//发送邮件
	this.sendEmail(email, user.Id)
	//4.返回输出
	this.Ctx.WriteString("注册成功，请去相应邮箱激活用户！")
}

func (this *UserController) ActiveReg() {
	id, err := this.GetInt("id")
	if common.PrintErr(err) {
		this.Data["errmsg"] = "要激活的用户不存在"
		this.TplName = "register.html"
		return
	}
	o := orm.NewOrm()
	var user models.User
	user.Id = id
	rerr := o.Read(&user)
	if rerr != nil {
		beego.Info(rerr)
		return
	}
	user.Active = true
	_, ierr := o.Update(&user)
	if ierr != nil {
		beego.Info(ierr)
		return
	}

	this.Redirect("/login", 302)
}

func (this *UserController) ShowLogin() {
	username := this.Ctx.GetCookie("username")
	temp, _ := base64.StdEncoding.DecodeString(username)
	if string(temp) == "" {
		this.Data["username"] = ""
		this.Data["checked"] = ""
	} else {
		this.Data["username"] = string(temp)
		this.Data["checked"] = "checked"
	}
	this.TplName = "login.html"
}

func (this *UserController) HandleLogin() {
	//1.获取数据
	username := this.GetString("username")
	pwd := this.GetString("pwd")

	if username == "" || pwd == "" {
		this.Data["errmsg"] = "登陆输入不完整，请重新输入"
		this.TplName = "login.html"
		return
	}

	o := orm.NewOrm()
	var user models.User
	user.Name = username
	err := o.Read(&user, "Name")

	if err != nil {
		this.Data["errmsg"] = "要激活的用户不存在"
		this.TplName = "login.html"
		return
	}
	if user.PassWord != pwd {
		this.Data["errmsg"] = "用户名或密码错误"
		this.TplName = "login.html"
		return
	}
	if user.Active != true {
		this.Data["errmsg"] = "用户未激活"
		this.TplName = "login.html"
		return
	}

	rem := this.GetString("remember")
	if rem == "on" {
		temp := base64.StdEncoding.EncodeToString([]byte(username))
		this.Ctx.SetCookie("username", temp, 24*3600*30)
	} else {
		this.Ctx.SetCookie("username", username, -1)
	}
	//1.跳转到首页
	//2.登陆判断
	//3.首页显示
	this.SetSession("username", username)
	this.Redirect("/", 302)
	//4.三个页面
	//视图布局
	//添加地址页（如何让页面只显示一个地址）
	//用户中心信息页显示
}

//退出登陆
func (this *UserController) Logout() {
	this.DelSession("username")
	this.Redirect("/", 302)
}

func (this *UserController) ShowUserCenter() {
	username := GetUser(&this.Controller)

	o := orm.NewOrm()
	var addr models.Address
	o.QueryTable("Address").RelatedSel("User").
	Filter("User__Name", username).Filter("Isdefault", true).One(&addr)

	if addr.Id == 0 {
		this.Data["addr"] = ""
	}else{
		this.Data["addr"] = addr
	}
	//获取用户信息页
	conn, err := redis.Dial(models.GetRedisAddr())
	if err != nil{
		beego.Info("redis连接错误", err)
	}else{
		o := orm.NewOrm()
		var user models.User
		user.Name = username
		o.Read(&user, "Name")
		conn.Send("lrange", "history_" + strconv.Itoa(user.Id), 0, 9)
		conn.Flush()//把缓冲区命令发到服务器
		res,_ := redis.Ints(conn.Receive())

		historys := make([]models.GoodsSKU, 0)
		for _, val := range res{
			var goods models.GoodsSKU
			goods.Id = val
			err := o.Read(&goods, "Id")
			if err != nil{
				continue
			}
			historys = append(historys, goods)
		}
		this.Data["historys"] = historys
		conn.Close()
	}

	this.Layout = "user_center_layout.html"
	this.TplName = "user_center_info.html"
}


func (this *UserController) ShowUserCenterOrder(){
	var user models.User
	user.Name = GetUser(&this.Controller)
	//获取订单表的数据
	o := orm.NewOrm()
	var orderInfos []models.OrderInfo

	o.Read(&user, "Name")

	o.QueryTable("OrderInfo").RelatedSel("User").Filter("User", user).All(&orderInfos)

	goodsBuffer := make([]map[string]interface{}, len(orderInfos))

	for index, val := range orderInfos{
		var orderGoods []models.OrderGoods
		o.QueryTable("OrderGoods").RelatedSel("OrderInfo", "GoodsSKU").Filter("OrderInfo", val).All(&orderGoods)

		temp := make(map[string]interface{})
		temp["orderInfo"] = val
		temp["orderGoods"] = orderGoods
		goodsBuffer[index] = temp
	}


	//分页
	allNum := len(goodsBuffer)
	//每页显示5个
	perPageShow := 2

	pageNum := allNum / perPageShow
	if pageNum < perPageShow{
		pageNum = 1
	}else if allNum % perPageShow != 0{
		pageNum += 1
	}
	pages := make([]int, pageNum)
	for i := 0; i < pageNum; i++{
		pages[i] = i + 1
	}
	nowPage, err := this.GetInt("page")
	if err != nil || nowPage < 1{
		nowPage = 1
	}
	if nowPage > pageNum{
		nowPage = pageNum
	}
	prePage := nowPage - 1
	nextPage := nowPage + 1

	endNum := nowPage * perPageShow
	if endNum > len(goodsBuffer){
		endNum = len(goodsBuffer)
	}
	this.Data["goodsBuffer"] = goodsBuffer[(nowPage - 1) * perPageShow : endNum]
	this.Data["pages"] = pages
	this.Data["prePage"] = prePage
	this.Data["nextPage"] = nextPage
	this.Data["activePage"] = nowPage
	this.Layout = "user_center_layout.html"
	this.TplName = "user_center_order.html"
}

func (this *UserController) ShowUserCenterSite(){
	username := GetUser(&this.Controller)

	o := orm.NewOrm()
	var addr models.Address
	o.QueryTable("Address").RelatedSel("User").Filter("User__Name", username).Filter("Isdefault", true).One(&addr)


	if addr.Id == 0 {
		this.Data["addr"] = ""
	}else{
		this.Data["addr"] = addr
	}

	this.Layout = "user_center_layout.html"
	this.TplName = "user_center_site.html"
}
func (this *UserController) HandleUserCenterSite(){
	username := GetUser(&this.Controller)

	var user models.User
	user.Name = username
	o := orm.NewOrm()
	err := o.Read(&user, "Name")
	if err != nil{
		beego.Info("没有此用户")
		this.Redirect("/user/center_site", 302)
		return
	}


	receiver := this.GetString("receiver")
	addr := this.GetString("addr")
	zipcode := this.GetString("zipcode")
	phone := this.GetString("phone")

	if receiver == "" || addr == "" || zipcode == "" || phone == ""{
		beego.Info("添加数据不完整")
		this.Redirect("/user/center_site", 302)
		return
	}


	var addrUser models.Address
	//addrUser.Isdefault = true
	//addrUser.User = &user
	//err = o.Read(&addrUser, "User", "Isdefault")
	if error := o.QueryTable("Address").RelatedSel("User").Filter("User__Name", username).
		Filter("Isdefault", true).One(&addrUser); error == nil{

		addrUser.Isdefault = false
		o.Update(&addrUser)
	}

	var addrUserNew models.Address
	addrUserNew.Addr = addr
	addrUserNew.Zipcode = zipcode
	addrUserNew.Receiver = receiver
	addrUserNew.Phone = phone
	addrUserNew.User = &user
	addrUserNew.Isdefault = true
	o.Insert(&addrUserNew)

	this.Redirect("/user/center_site", 302)
}